package com.ease.access.workbench.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.ease.access.workbench.service.CoolActionAccessService;
import com.ease.access.workbench.service.CoolMenuAccessService;
import com.ease.common.vo.Ordering;
import com.ease.model.term.CoolAction;
import com.ease.model.term.CoolMenu;
import com.ease.platform.access.service.impl.AbstractParameterizedBeanIbatisAccessServiceImpl;
import com.obas.platform.workbench.util.ActionParameterStructureUtil;

public class CoolMenuAccessServiceImpl extends AbstractParameterizedBeanIbatisAccessServiceImpl<CoolMenu> implements CoolMenuAccessService {

	@Autowired
	private CoolActionAccessService coolActionAccessService;

	@Override
	public List<CoolMenu> findByParentId(long parentId) {
		if (parentId > 0) {
			Map<String, Object> parameter = new HashMap<String, Object>();

			parameter.put("parentCoolMenuId", parentId);
			List<CoolMenu> allCoolMenuList = this.find("findByParentId", parameter, (Ordering) null);

			if (null == allCoolMenuList)
				return null;

			List<CoolMenu> coolMenus = getChildCoolMenus(parentId, allCoolMenuList);

			return coolMenus;
		}
		return null;
	}

	private List<CoolMenu> getChildCoolMenus(long parentId, List<CoolMenu> allCoolMenuList) {
		List<CoolMenu> result = new ArrayList<CoolMenu>();

		for (CoolMenu coolMenu : allCoolMenuList) {
			if (coolMenu.getActionId() > 0) {
				CoolAction action = coolActionAccessService.findById(coolMenu.getActionId());
				coolMenu.setAction(action);
				Map<String, Object> actionParameterMap = new HashMap<String, Object>();
				ActionParameterStructureUtil.generateParameterMap(action.getParameter(), actionParameterMap);
				Map<String, Object> menuParameterMap = new HashMap<String, Object>();
				ActionParameterStructureUtil.generateParameterMap(coolMenu.getParameter(), menuParameterMap);
				menuParameterMap.putAll(actionParameterMap);
				coolMenu.setParameterMap(menuParameterMap);
			}
			if (coolMenu.getParentCoolMenuId() == parentId) {
				result.add(coolMenu);
				List<CoolMenu> childCoolMenus = getChildCoolMenus(coolMenu.getId(), allCoolMenuList);
				coolMenu.setChildrenCoolMenus(childCoolMenus);
			}
		}

		return result;
	}

	/**
	 * @return the coolActionAccessService
	 */
	public CoolActionAccessService getCoolActionAccessService() {
		return coolActionAccessService;
	}

	/**
	 * @param coolActionAccessService
	 *            the coolActionAccessService to set
	 */
	public void setCoolActionAccessService(CoolActionAccessService coolActionAccessService) {
		this.coolActionAccessService = coolActionAccessService;
	}

}
